import React from 'react'
import { Button, CircularProgress } from '@material-ui/core'
import { ButtonProps } from '@material-ui/core/Button'
import styled from 'styled-components'

interface Props extends ButtonProps {
  loading?: boolean;
}

interface WrapperProps {
  fullWidth?: boolean;
}

const Wrapper = styled.div<WrapperProps>`
  position: relative;
  display: inline-flex;
  width: ${props => props.fullWidth ? '100%' : 'auto' };
`

const StyledCircularProgress = styled(CircularProgress)`
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -12px;
  margin-left: -12px;
`

const LoadingButton: React.FC<Props> = ({
  loading = false,
  children,
  color,
  variant,
  fullWidth,
  ...rest
}) => {
  return (
    <Wrapper fullWidth={fullWidth}>
      <Button
        variant={'contained' || variant}
        color={'primary' || color}
        disabled={loading}
        fullWidth={fullWidth}
        {...rest}
      >
        {children}
      </Button>
      {loading && <StyledCircularProgress size={24} />}
    </Wrapper>
  )
}

export default LoadingButton
